package com.guoxin.part4.chapter18;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author guoxin
 * @date 2019/8/31
 */
public final class IntegerAccumulatorImprove {
    private final int init;

    //构造时传入初始值
    public IntegerAccumulatorImprove(int init) {
        this.init = init;
    }

    public IntegerAccumulatorImprove(IntegerAccumulatorImprove accumulatorImprove, int init) {
        this.init = accumulatorImprove.getValue() + init;
    }

    public IntegerAccumulatorImprove add(int i) {
        return new IntegerAccumulatorImprove(this, i);
    }

    public int getValue() {
        return this.init;
    }

    public static void main(String[] args) {
        IntegerAccumulatorImprove accumulatorImprove = new IntegerAccumulatorImprove(0);
        IntStream.range(0, 3).forEach(i -> {
            new Thread(() -> {
                int inc = 0;
                while (true) {
                    int oldValue = accumulatorImprove.getValue();
                    int result = accumulatorImprove.add(inc).getValue();
                    System.out.println(oldValue + "+" + inc + "=" + result);
                    if (inc + oldValue != result) {
                        System.err.println("ERROR:" + oldValue + "+" + inc + "=" + result);
                    }
                    inc++;
                    slowly();
                }
            }).start();
        });
    }

    private static void slowly() {
        try {
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
